/*
 * scheduler.c
 * 
 * Copyright 2012 Laura <arual13@gmail.com>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301, USA.
 * 
 * 
 */


#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include "lib/scheduler.h"

//~ int main(int argc, char **argv)
//~ {
    //~ /* Load configuration */
    //~ configuration *config = getConfigParams();
    //~ 
    //~ /* Initialize the seed for random nums */
    //~ srand(time(NULL));
    //~ 
    //~ if(config == NULL)
        //~ printf("%s\n","Error: Couldn't load the configuration file.");
    //~ else{
        //~ printf("%s\n","Initializing the scheduler...");
        //~ runScheduler(config);        
    //~ }
    //~ 
    //~ return 0;
//~ }

/* 
 * -Ready Queue: Initialized threads from the GUI - printQueue(readyQueue);
 * -Wait Queue: When threads stops using CPU and still have work to do..
 * -Running Queue: the thread that is running 
 * -Finish Queue: threads that finished, they don't participate in the raffle'
 */
 
int runScheduler(configuration *config)
{
    /* Scheduler Queues */    
    threadQueue* readyQueue = initializeThreads(config);
    threadQueue* runQueue =  newQueue(config->threads_num);
    threadQueue* waitQueue = newQueue(config->threads_num);
    threadQueue* finishQueue =  newQueue(config->threads_num);
    threadQueue* sourceQueue = readyQueue;
    threadNode* winner;
    long int lotteryMax = 0; // Total number of tickets
    
    for (long int i = 0; i < config->threads_num; i++) {
        lotteryMax += config->tickets_num[i];
    }
    
    printf("\nRunning in mode: %i \n", config->mode);
    
    /* While there are jobs to process*/
    while(readyQueue->head != NULL || waitQueue->head != NULL || runQueue->head != NULL) {
        
        long int number = getLotteryNum(lotteryMax);
        printf("Lottery: %ld \n",number);
        
        /* Selects the thread */
        sourceQueue = readyQueue;
        winner = getNextProcess(sourceQueue,number);
        
        /* We can add a tag to the queue to know which one it corresponds*/
        if (winner == NULL) {
            sourceQueue = waitQueue;
            winner = getNextProcess(sourceQueue,number);
        }
        
        /* Probably the process already finished */
        if (winner != NULL) {
            
            printf("Tread %ld wins! \n", winner->id);           
            
            if(winner->work_units == 0) {
                printf("Thread %ld finished...\n", winner->id);
                moveElement(sourceQueue,finishQueue,winner);
                /* TODO EDU: Update in this case from the handler
                gchar *str = g_strdup_printf("%.0f%%, Pi: %Lf", 100.0, currentThread->current_result);
                printf("Something: %s\n", str);
                gpointer *pbar = g_ptr_array_index(config->thread_progressbars, currentThread->id);
                gtk_progress_bar_set_text(GTK_PROGRESS_BAR(pbar), str);
                * */
            }else {
            
                /* Sends the process to run, if they are in ready, send otherwise resubmit */
                moveElement(sourceQueue,runQueue,winner);
                
                
                /* TODO: PREEMPTIVE MODE*/
                if(config->mode == 1) {
                    printf("Waiting...\n");
                    usleep(SECOND);
                /* 
                 * TODO: Pause the handler, start the thread, patch timer, wake up the thread!!! 
                 */
                } 
                
                /* NON-PREEMPTIVE MODE*/
                else {
        
                    long double percentage = config->quantum/(double)100;
                    units_to_complete = percentage*winner->work_units;
                    
                    if ( units_to_complete == 0 ) {
                        units_to_complete = 1;
                    } else if ((winner->work_left - units_to_complete) < 0) {
                        units_to_complete = winner->work_left;
                    }
                    
                    printf("\nRunning thread %ld...\n", winner->id);
                    pause_handler();
                    start_thread(winner);
                    printf("The thread came back!\n");
                    //pause_thread(winner); /* Pause the thread */
                    
                    /*Update the thread job!*/
                    
                    if ( units_to_complete == 0 ) {
                        winner->work_left -= 1;
                    } else if ((winner->work_left - units_to_complete) < 0) {
                        winner->work_left = 0;
                    } else {
                        winner->work_left -= units_to_complete;
                    }
                    
                    winner->current_result += pi_result; /* TODO: Do something to the result*/
                    printf("Units Completed: %ld Result: %Lf\n",units_to_complete, winner->current_result);

                }
                
                printf("Checking the result...\n");
                
                /* If there is still work to do, move it to waiting */
                if(winner->work_left > 0) {
                    
                    printf("Still there are %ld units to complete...\n", winner->work_left);
                   
                    moveElement(runQueue,waitQueue,winner);
                    
                }
                /* No work, then it already finished */
                else{
                    printf("Thread %ld finished...\n", winner->id);
                    moveElement(runQueue,finishQueue,winner);
                }
            
        }
    }
    }
    
    
    printf("Done!\n");
      
    /* Release unsed memory 
    */
    freeQueue(readyQueue);
    freeQueue(waitQueue);
    freeQueue(runQueue);
    freeQueue(finishQueue);
    
    return 0;
    
    
}

threadNode *getNextProcess(threadQueue* queue, int num)
{
    threadNode *node = getWinner(queue,num);

    return node;
        
}



long int getLotteryNum(long int limit)
{
    return rand()%limit; 
}


threadNode* getWinner(threadQueue* list, long int ticket)
{
    long int i;
    threadNode *node = NULL; 
    
    for(node = list->head; node; node = node->next) {
        
        long int tickets_num = node->tickets_num;
        
        for(i=0; i<tickets_num; i++)
        {
            if(ticket == node->tickets[i]) {
                return node;
            }
			/*printf("Looking Winner: %i \n", node->id);*/
        }
    }
    
    return node;
        
}



int releaseMemory(configuration* config, threadQueue* pool)
{
    /*free(pool->threads);*/
    free(pool);
    free(config->tickets_num);
    free(config->work_units);
    free(config);
    
    return 0;
}



